package net.rlair.es.controller;

import net.rlair.es.model.Article;
import net.rlair.es.model.req.ArticleReq;
import net.rlair.es.repository.ArticleRepository;
import net.rlair.es.util.ServiceResult;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.client.Client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;


/**
 * index.
 *
 * @author yaoyi
 * @version 1.0.0.0
 */
@Controller
@RequestMapping("/")
public class IndexController {
    /**
     * 日志.
     */
    public static final Logger LOGGER = LoggerFactory.getLogger(IndexController.class);

    /**
     * 客户端.
     */
    @Resource
    private Client client;

    /**
     * dao.
     */
    @Resource
    private ArticleRepository articleRepository;

    /**
     * 首页.
     *
     * @param model 视图model
     * @return view
     */
    @RequestMapping("/")
    public String index(final Model model) {
        return "index";
    }

//    @ResponseBody
//    @RequestMapping("/createIndex")
//    public Object createIndex(final Model model, final Index index) {
//
//        final IndexResponse response = client.prepareIndex(index.getIndex(), index.getType()).get();
//
//        // 索引名称
//        String _index = response.getIndex();
//        // 类型名称
//        String _type = response.getType();
//        // 文档id
//        String _id = response.getId();
//        // 版本(if it's the first time you index this document, you will get: 1)
//        long _version = response.getVersion();
//        // 是否被创建is true if the document is a new one, false if it has been updated
//        boolean created = response.isCreated();
//        LOGGER.info("_index{}_type{}_id{}_version{}", _index, _type, _id, _version);
//        if(created){
//            return "Create success";
//        }else {
//            return "Create failed";
//        }
//
//    }

    /**
     * save.
     * @param articles articles
     * @return Object
     */
    @ResponseBody
    @RequestMapping(value="/article/save", method = RequestMethod.POST)
    public Object save(@RequestBody final List<Article> articles){
        if(CollectionUtils.isEmpty(articles)){
            return new ServiceResult<>(false);
        }
        final Iterable<Article> save = articleRepository.save(articles);
        for (Article article:save){
            LOGGER.error(article.getId()+"");
        }
        return new ServiceResult<>(true);
    }

    /**
     * search.
     * @param articleReq articleReq
     * @return Object
     */
    @ResponseBody
    @RequestMapping(value="/article/search", method = RequestMethod.POST)
    public Object search(@RequestBody final ArticleReq articleReq){
        final String key=articleReq.getKey();
        final int pageNo=articleReq.getPageNo()-1;
        final int pageSize=articleReq.getPageSize();
        final Pageable pageable = new PageRequest(pageNo, pageSize);
        Page<Article> pageObj=null;
        long count= 0;
        if (StringUtils.isBlank(key)) {
            //count = articleRepository.count();
            pageObj = articleRepository.findAll(pageable);
        } else {
            final List<String> strings = Arrays.asList(key.trim().split(" "));
            //count = articleRepository.countBySubjectInOrContentIn(strings, strings);
            pageObj = articleRepository.findBySubjectInOrContentIn(strings, strings, pageable);
        }
        count=pageObj.getTotalElements();
        //final int pages=pageObj.getTotalPages();
        final ServiceResult<List<Article>> ret = new ServiceResult<>(true, pageObj.getContent(), "成功");
        ret.setAdditionalProperties("totalRow", count);
        ret.setAdditionalProperties("req", articleReq);
        return ret;
    }
}
